// 配置项目中使用到的所有的中间件
const path = require('path');
const exphbs = require('express-handlebars');
const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const morgan = require('morgan');
const methodOverride = require('method-override');
const errorHandler = require('errorhandler');
const moment = require('moment');

// 导出函数使得app注册中间件
module.exports = function(app) {

    // 配置moment，并设置helper函数
    moment.locale('zh-cn');
    // 配置handlebars,使得模板引擎能够生效,并设置helper函数
    app.engine('handlebars',exphbs({
            helpers:{
                timeago: (timestamp) => {
                    return moment(timestamp).startOf('minute').fromNow();
                },
            },
        })
    );
    app.set('view engine','handlebars');
    app.use(morgan('dev'));
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json());
    app.use(methodOverride());
    app.use(cookieParser('secret-value'));
    app.use('/public/', express.static(path.join(__dirname, '../public')));
    if (app.get('env') === 'development') {
      app.use(errorHandler());
    }
    return app;
  };